<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>弹幕</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
        list-style: none;
        border: 0;
    }

    body {
        background: #bcbcbc;
    }

    .main {
        width: 600px;
        height: 400px;
        margin: 0 auto;
        position: relative;
    }

    .main img {
        position: absolute;
        right: 0;
        bottom: 0;
        width: 100px;
        height: 100px;
    }

    #canvas {
        display: block;
        background: #000;
    }
</style>
</head>

<body>
    <div class="main">
        <canvas id="canvas">嗨帅哥您的浏览器不支持canvas赶紧去升级吧</canvas>
    </div>
</body>
<script>
    //定义画布2d工作台
    var canvas = document.getElementById("canvas")
    var ctx = canvas.getContext("2d")
    //设置画布长宽
    canvas.width = 600
    canvas.height = 400
    //定义弹幕字体颜色
    var colorArr = ["yellow", "pink", "orange", "red", "green"];
    //定义弹幕文本
    var textArr = [
        "沙发、沙发、沙发",
        "今晚有没有LOL的一块啊？",
        "这种烟真心不好抽",
        "星期天我想去爬长城",
        "边喝酒边看电影",
        "如果有任何疑问可以扫码联系我哦！"
    ]
    //设置弹幕字体大小
    ctx.font = "20px Courier New"
    //设置弹幕出现的坐标
    var arryX = [80, 100, 5, 300, 500, 430];//初始的X
    var arryY = [80, 100, 20, 300, 380, 210];//初始的Y
    //设置定时器（需要不停地向左移动）
    setInterval(function () {
        //清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        //保存状态
        ctx.save();
        //使用for循环遍历所有文本
        for (var i = 0; i < textArr.length; i++) {
            //改变x轴坐标
            arryX[i] -= (i + 1) * 0.6;
            ctx.fillStyle = colorArr[i];
            ctx.fillText(textArr[i], arryX[i], arryY[i])
        }
        for (var j = 0; j < textArr.length; j++) {
            if (arryX[j] <= -500) {
                arryX[j] = canvas.width;
            }
        }
        ctx.restore();
    }, 30)
</script>

</html>